// 数据接口域名

import axios from 'axios';
import qs from 'qs';
import { getCookie } from '@/tim';
axios.defaults.withCredentials = true

export const apiUrl = process.env.NODE_ENV === 'production' ? '/admin-server' : '/admin-server';
// export const apiUrl = process.env.NODE_ENV === 'production' ? '/api' : '/api';

axios.interceptors.request.use(
  async (response) => {
    if (getCookie('fp') != 'undefined') {
      response.headers['fp'] = `${getCookie('fp')}`
    }
    return response
  },
  error => {
    console.log(error) // for debug
  }
);

function formatUrl (data) {
  var str = '?';
  Object.keys(data).forEach((v) => {
    str += `${v}=${data[v]}&`
  });
  return str.substring(0, str.length - 1);
}

const getData = function (url, data = {}, resolve, reject) {
  console.log(getCookie('fp'), 'fp');
  url = url + formatUrl(data);
  return axios.get(url, {
    headers: {
      'Authorization': getCookie('token')
    }
  }).then((res) => {
    resolve(res);
  }).catch((msg) => {
    reject(msg);
  });
};

var get = function (url, data = {}) {
  return new Promise((resolve, reject) => {
    getData(url, data, resolve, reject);
  })
}

const postData = function (url, data = {}, resolve, reject) {
  url = apiUrl + url;
  return axios.post(url, JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': getCookie('token')
    }
  }).then((res) => {
    resolve(res);
  }).catch((msg) => {
    reject(msg);
  });
};

var post = function (url, data = {}) {
  return new Promise((resolve, reject) => {
    postData(url, data, resolve, reject);
  })
}

const postDataForm = function (url, data = {}, resolve, reject) {
  url = apiUrl + url;
  return axios.post(url, qs.stringify(data), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      'Authorization': getCookie('token')
    }
  }).then((res) => {
    resolve(res);
  }).catch((msg) => {
    reject(msg);
  });
};

var postForm = function (url, data = {}) {
  return new Promise((resolve, reject) => {
    postDataForm(url, data, resolve, reject);
  })
}

var postMultiForm = function (url, data = {}) {
  return new Promise((resolve, reject) => {
    postDataFormMulti(url, data, resolve, reject);
  })
}

const postDataFormMulti = function (url, data = {}, resolve, reject) {
  url = apiUrl + url;
  axios.defaults.timeout = 1000 * 60 * 60;
  return axios.post(url, data, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': getCookie('token')
    }
  }).then((res) => {
    resolve(res);
  }).catch((msg) => {
    reject(msg);
  });
};

export default {
  get,
  post,
  postForm,
  postMultiForm,
  apiUrl,
}
